/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.replication;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataDto;
import com.inspur.edp.sgf.api.common.ResourceType;
import com.inspur.edp.sgf.api.entity.SgMetadata;
import com.inspur.edp.sgf.api.service.EapiMetadataDtService;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.metadata.MetadataGetterParameter;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.constant.I18nExceptionConstant;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 *
 * @author Noah Guo
 * @date 2021/02/26
 */
class FormMetadataVoManager {
    public static void copyFormMetadataVo(MetadataReplicationContext context, GspMetadata sourceFormMetadata,
                                          MetadataDto targetMetadataDescription, FormDOM replicateFormDOM, boolean isDebug) {
        ArrayList<HashMap<String, Object>> schemaCollection = replicateFormDOM.getModule().getSchemas();
        if (schemaCollection != null && !schemaCollection.isEmpty()) {
            for (HashMap<String, Object> schema : schemaCollection) {
                // 1.1 获取并拷贝VO
                String viewObjectId = schema.containsKey("id") ? schema.get("id").toString() : "";
                if (StringUtility.isNullOrEmpty(viewObjectId)) {
                    // 如果不存在对应的voId  那么无法进行vo拷贝
                    continue;
                }
                String voSpacePath = StringUtility.getOrDefault(schema.get("voPath"), sourceFormMetadata.getRelativePath());
                String voNameSpace = StringUtility.getOrDefault(schema.get("voNameSpace"), sourceFormMetadata.getHeader().getNameSpace());
                MetadataGetterParameter metadataGetterParameter = MetadataGetterParameter.getNewInstance(viewObjectId, voSpacePath, MetadataTypeEnum.ViewModel);
                metadataGetterParameter.setTargetMetadataCode(StringUtility.getOrDefault(schema.get("code"), ""));
                metadataGetterParameter.setTargetMetadataName(StringUtility.getOrDefault(schema.get("name"), ""));
                metadataGetterParameter.setTargetMetadataNamespace(voNameSpace);
                metadataGetterParameter.setSourceMetadata(sourceFormMetadata, MetadataTypeEnum.Frm);

                GspMetadata viewObjectMetadata = MetadataUtility.getInstance().getMetadataWithDesign(metadataGetterParameter);
                if (viewObjectMetadata == null) {
                    throw new WebCustomException(I18nExceptionConstant.WEB_FORM_METADATA_ERROR_0011, new String[]{viewObjectId});
                }
                MetadataDto viewObjectMetadataDto = new MetadataDto();
                // vo默认后缀_frm
                String targetVoSuffix = "_frm";
                viewObjectMetadataDto.setCode(targetMetadataDescription.getCode() + targetVoSuffix);
                viewObjectMetadataDto.setName(targetMetadataDescription.getName() + targetVoSuffix);
                viewObjectMetadataDto.setProjectName(targetMetadataDescription.getProjectName());
                viewObjectMetadataDto.setRelativePath(targetMetadataDescription.getRelativePath());
                viewObjectMetadataDto.setNameLanguage(targetMetadataDescription.getNameLanguage());

                MetadataReplicationContext viewObjectMetadataReplicationContext = new MetadataReplicationContext();
                viewObjectMetadataReplicationContext.setSourceProjectName(context.getSourceProjectName());
                viewObjectMetadataReplicationContext.setSourceMetadata(viewObjectMetadata);
                viewObjectMetadataReplicationContext.setTargetMetadataDescription(viewObjectMetadataDto);

                // 复制vo元数据
                GspMetadata replicateViewObjectMetadata = MetadataCloneManager.cloneMetadata(viewObjectMetadataReplicationContext);
                context.getReplicationResult().addAll(viewObjectMetadataReplicationContext.getReplicationResult());

                // 为了避免删除vo元数据时依赖eapi  先进行删除eapi
                MetadataUtility.getInstance().createMetadataIfNotExistsWithDesign(replicateViewObjectMetadata);

                MetadataUtility.getInstance().saveMetadataWithDesign(replicateViewObjectMetadata);

                // 更新表单内容关联VO
                schema.put("id", replicateViewObjectMetadata.getHeader().getId());


                EapiMetadataDtService eapiMetadataDtService = SpringBeanUtils.getBean(EapiMetadataDtService.class);
                GspMetadata metadata = eapiMetadataDtService.create(replicateViewObjectMetadata, replicateViewObjectMetadata.getRelativePath(), ResourceType.VO_ADVANCE);
                SgMetadata eapiMetadata = (SgMetadata) metadata.getContent();
                // 1.3 更新表单关联epaiId
                schema.put("eapiId", eapiMetadata.getId());

                // 更新其他属性
                schema.put("code", schema.get("code").toString().replace(sourceFormMetadata.getHeader().getCode(), targetMetadataDescription.getCode()));
                schema.put("name", schema.get("name").toString().replace(sourceFormMetadata.getHeader().getName(), targetMetadataDescription.getName()));

                String sourceUri = removeLastSegment(schema.get("sourceUri").toString());
                sourceUri = sourceUri + "/" + viewObjectMetadataDto.getCode().toLowerCase();
                schema.put("sourceUri", sourceUri);
            }
        }
    }

    public static String removeLastSegment(String url) {
        int lastSlashIndex = url.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            return url.substring(0, lastSlashIndex);
        }
        return url; // 如果没有找到 '/', 返回原字符串
    }

}
